__author__ = 'longlong'
import socket
import sys
import threading

data = ''
con = threading.Condition()
HOST = input('Please input your host name:')
PORT = 9000
ADDR = (HOST, PORT)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(ADDR)
s.listen(10)

def clientThreadIn(conn, nick):
    global data
    while True:
        try:
            temp = conn.recv(1024).decode()
            if temp == nick+':'+'exit':
                conn.close()
            NotifyAll(temp)
        except:
            NotifyAll(nick+' leave the room')
            s.close()
            break


def NotifyAll(temp):
    global data
    if con.acquire():
        data = temp
        con.notifyAll()
        con.release()


def clientThreadOut(conn, nick):
    global data
    while True:
        if con.acquire():
            con.wait()
            if data:
                try:
                    conn.send(data.encode())
                    con.release()
                except:
                    con.release()
                    return

while True:
    conn, addr = s.accept()
    nick = conn.recv(1024).decode()
    print('connent with', addr)
    NotifyAll('welcome join us '+nick)
    conn.send(data.encode())
    threading.Thread(target=clientThreadIn, args=(conn, nick)).start()
    threading.Thread(target=clientThreadOut, args=(conn, nick)).start()